var tgd = tgd || {};
tgd.Contests = tgd.Contests || {};
tgd.Contests.Darts = tgd.Contests.Darts || {};

tgd.Contests.Darts.Controller = function () {

	this.rsf = [];  //random solution factories that will be added via menu
	this.vws = [];  //todo:  don't need this?
	this._bestView = new tgd.Contests.Darts.Views.BestScores(document.getElementById("best"));
	this._txtNumDarts = document.getElementById("txtNumDarts");
	this._txtNumRegions= document.getElementById("txtNumRegions");
	this._txtMaxRegVal = document.getElementById("txtMaxRegVal");
	this._txtManNumDarts = document.getElementById("txtManNumDarts");
	this._txtManRegions = document.getElementById("txtManRegions");
	this._manResults = document.getElementById("manResults");
	this._manFactory = new tgd.Contests.Darts.ManualFactory()

	this._txtNumDarts.focus();

	if (tgd.Contests.Darts.Controller._initialized === undefined) {

		//todo: rename
		tgd.Contests.Darts.Controller.prototype.addThing = function() {
			var liveViewDiv = document.getElementById("live");
			var newDiv = document.createElement("div");
			liveViewDiv.appendChild(newDiv);

			var newRSF = new tgd.Contests.Darts.RandomSolutionFactory(parseInt(this._txtNumDarts.value), parseInt(this._txtNumRegions.value), parseInt(this._txtMaxRegVal.value));

			var liveView = new tgd.Contests.Darts.Views.AllScores(newDiv, 5);  //todo: configure number of rows
			liveView.registerCallback({ onStart: function() {newRSF.start();}, onStop: function() {newRSF.stop();} });
			this.vws.push(liveView);

			var self = this;
			newRSF.registerCallback(function(s) { self._bestView.onUpdate(s);liveView.onUpdate(s); });
			this.rsf.push(newRSF);

			newRSF.start();
			
			this._txtNumDarts.value = this._txtNumRegions.value = this._txtMaxRegVal.value = "";
			this._txtNumDarts.focus();
		}

		tgd.Contests.Darts.Controller.prototype.addManualSolution = function() {
			var self = this;
			var sss = this._txtManRegions.value.split(",");
			for (var i = 0; i < sss.length; sss[i] = parseInt(sss[i++]));

			this._manFactory.setConfig({ 
				NumDarts: parseInt(this._txtManNumDarts.value), 
				Regions: sss, 
				Callback: function(s) { 
					self._bestView.onUpdate(s);
					self._manResults.innerHTML = "(D, R, S) = " + s.getNumDarts() + ", " + s.getNumRegions() + ", " + s.getSmallestScoreUnattainable() + "    ---    " + s;
				}
			});
			this._manFactory.generateSolution();
		}

		tgd.Contests.Darts.Controller._initialized = true;
	}
};